package webapp;

import java.util.ArrayList;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import flca.mda.api.util.NameUtils;
import flca.mda.codegen.data.ITemplate;
import flca.mda.codegen.helpers.IPostProcess;
import flca.mda.codegen.helpers.SourceCodeUtils;

public class RemoveNotUsedImportsPostprocessor implements IPostProcess
{
	private static SourceCodeUtils su = new SourceCodeUtils();
	private static NameUtils nu = new NameUtils();
	
	private Collection<String> linesWithoutImports;
	
	@Override
	public String parse(String aInput, ITemplate aTemplate, Class<?> aTargetClass)
	{
		String result = aInput;
		StringBuffer sb = new StringBuffer();

		linesWithoutImports = getLinesWithoutImports(aInput);
		Collection<String> lines = su.getSourcecodeLines(result);

		for (String line : lines) {
			if (su.isImportStatement(line)) {
				String clsname = nu.getSimplename(su.getImportClassname(line));
				if (clsname == null || nameFound(clsname)) {
					sb.append(line + "\n");
				} // else we skip this import
			} else {
				sb.append(line + "\n");
			}
		}
		return sb.toString();
	}

	
	@Override
	public boolean isApplicable(ITemplate aTemplate) {
		return true;
	}


	private boolean nameFound(String aName)
	{
		Pattern p = Pattern.compile("\\b"  + aName + "\\b");

		for (String line : linesWithoutImports) {
			Matcher m = p.matcher(line);
			if (m.find()) {
				return true;
			}
		}

		return false;
	}
	
	private Collection<String> getLinesWithoutImports(String aInput) 
	{
		Collection<String> result = new ArrayList<String>();
		
		Collection<String> lines = su.getFormattedSourcecodeLines(aInput);
		for (String line : lines) {
			if (!su.isImportStatement(line)) {
				result.add(line);
			}
		}
		return result;
	}
	
}
